package com.fengniaoxls.fengniaonewretail;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.fengniaoxls.fengniaonewretail.app.App;
import com.fengniaoxls.fengniaonewretail.base.BaseAbstractSimpleActivity;
import com.fengniaoxls.fengniaonewretail.base.IActivityStatusBar;
import com.fengniaoxls.fengniaonewretail.commom.constants.Constants;
import com.fengniaoxls.fengniaonewretail.jpush.FNIntentService;
import com.fengniaoxls.fengniaonewretail.jpush.VoiceAccessibilityService;
import com.fengniaoxls.fengniaonewretail.jpush.voice.VoiceSpeaker;
import com.fengniaoxls.fengniaonewretail.jpush.voice.service.KeepLiveVoiceService;
import com.fengniaoxls.fengniaonewretail.jpush.voice.service.ServiceUtils;
import com.fengniaoxls.fengniaonewretail.net.resonse.HttpResult;
import com.fengniaoxls.fengniaonewretail.property.BatteryWhiteList;
import com.fengniaoxls.fengniaonewretail.property.SystemSetting;
import com.fengniaoxls.fengniaonewretail.utils.SPUtils;
import com.fengniaoxls.fengniaonewretail.utils.ToastUtil;
import com.fengniaoxls.fengniaonewretail.utils.imagepick.BitmapUtil;
import com.fengniaoxls.fengniaonewretail.utils.imagepick.ICompressImageResponse;
import com.fengniaoxls.fengniaonewretail.utils.imagepick.ImageSelector;
import com.fengniaoxls.fengniaonewretail.utils.imagepick.PermissionUtils;
import com.fengniaoxls.fengniaonewretail.utils.imagepick.popup.PopupGetPictureView;
import com.fengniaoxls.fengniaonewretail.webview.CustomWebView;
import com.freak.httphelper.ApiCallback;
import com.freak.httphelper.SubscriberCallBack;
import com.freak.httphelper.log.LogUtil;
import com.igexin.sdk.PushManager;
import com.just.agentweb.AbsAgentWebSettings;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.IAgentWebSettings;
import com.just.agentweb.LogUtils;
import com.just.agentweb.WebListenerManager;
import com.just.agentweb.download.AgentWebDownloader;
import com.just.agentweb.download.DefaultDownloadImpl;
import com.just.agentweb.download.DownloadListenerAdapter;
import com.just.agentweb.download.DownloadingService;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.fengniaoxls.fengniaonewretail.utils.imagepick.ImageSelector.CUT_PHOTO;
import static com.fengniaoxls.fengniaonewretail.utils.imagepick.ImageSelector.GET_PICTURE_SELECT_PHOTO;
import static com.fengniaoxls.fengniaonewretail.utils.imagepick.ImageSelector.GET_PICTURE_TAKE_PHOTO;


public class MainNewActivity extends BaseAbstractSimpleActivity implements IActivityStatusBar {
    private String url = "";
    private AgentWeb mAgentWeb;
    private LinearLayout mLinearLayoutHomepageWebView;
    private DownloadingService mDownloadingService;
    //    private WebView mWebView;
    private CustomWebView mWebView;
    private ValueCallback<Uri[]> mUploadCallbackAboveFive;
    private ValueCallback<Uri> mUploadMessage;
    private File userImgFile;
    private boolean isRefresh = false;
    /**
     * 请求开启定位
     */
    public static int REQUEST_CODE_ENABLE_LOCATION = 100;
    public static int REQUEST_CODE_ACCESS_LOCATION_PERMISSION = 101;
    private LocationWebChromeClient mWebChromeClient;
    private static final int SCAN_REQUEST_CODE = 20000;
    public static final int SCAN_RESULT_CODE = 20001;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    private HttpResult mHttpResult;
    private PowerManager.WakeLock wakeLock = null;
    private long mTime;

    @Override
    protected int getLayout() {
        return R.layout.activity_main_new;
    }

    @Override
    protected void initEventAndData() {

    }

    @Override
    protected void onDestroyRelease() {
stopVoiceService();
    }

    private void requestPermission() {
        new RxPermissions(this)
                .requestEach(Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new SubscriberCallBack<>(new ApiCallback<Permission>() {
                    @Override
                    public void onSuccess(Permission model) {
                        if (model.granted) {

                        } else {
//                            ToastUtil.shortShow("没有开启权限，部分功能将无法使用");
//                            finish();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                }));
    }

    @Override
    protected void initView() {
        //保持后台唤醒
        try {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            assert pm != null;
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MainNewActivity.class.getName());
            wakeLock.acquire();
        } catch (Exception e) {
            e.printStackTrace();
        }
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), FNIntentService.class);
        //检查并跳转到辅助功能
        if (!VoiceAccessibilityService.isStart()){
            try {
                mActivity.startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
            } catch (Exception e) {
                mActivity.startActivity(new Intent(Settings.ACTION_SETTINGS));
                e.printStackTrace();
            }
        }
        requestPermission();
//        if (!TextUtils.isEmpty((String) SPUtils.get(App.getInstance().getApplicationContext(), Constants.USER_CODE, ""))) {
//            if ((boolean) SPUtils.get(App.getInstance().getApplicationContext(), (String) SPUtils.get(App.getInstance().getApplicationContext(), Constants.USER_CODE, "") + Constants.VOICE_OPEN_STATUS, false)) {
//                if (!isStartService()) {
//                    startService(new Intent(this, KeepLiveVoiceService.class));
////                             Android 8.0使用startForegroundService在前台启动新服务
////                    Intent voiceService = new Intent(this, VoiceService.class);
////                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
////                        startForegroundService(voiceService);
////                    } else {
////                        startService(voiceService);
////                    }
//                }
//            }
//        }
//        if (!isStartService()) {
            startService(new Intent(this, KeepLiveVoiceService.class));
//                             Android 8.0使用startForegroundService在前台启动新服务
//                    Intent voiceService = new Intent(this, VoiceService.class);
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                        startForegroundService(voiceService);
//                    } else {
//                        startService(voiceService);
//                    }
//        }
//        url = Constants.getBaseUrl(Constants.SERVER_TYPE) + "index.html?access_token=" + SPUtils.get(MainNewActivity.this, Constants.ACCESS_TOKEN, "");
        LogUtil.e("开始加载");
        url = "https://d.818fn.com";
//        url = "http://dtest.818fn.com/";
        mLinearLayoutHomepageWebView = findViewById(R.id.linear_layout_main_web_view);
        mWebChromeClient = new LocationWebChromeClient();
        mWebView = new CustomWebView(MainNewActivity.this);

        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mLinearLayoutHomepageWebView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .useDefaultIndicator(-1, 3)
                .setWebView(mWebView)
                .setAgentWebWebSettings(getSettings())
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(mWebChromeClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setMainFrameErrorView(R.layout.view_load_error, -1)
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)
                .interceptUnkownUrl()
                .createAgentWeb()
                .ready();
        mAgentWeb = mPreAgentWeb.go(url);
//        mWebView = mAgentWeb.getWebCreator().getWebView();
        mAgentWeb.getAgentWebSettings().getWebSettings().setUserAgentString(mAgentWeb.getAgentWebSettings().getWebSettings().getUserAgentString().concat("fn-Android-APP"));
        mAgentWeb.getJsInterfaceHolder().addJavaObject("fnxls", new JavaScriptInterface(this));
        if (url.contains("<html>")) {
            mWebView.loadDataWithBaseURL(null, url.toString(), "text/html", "utf-8", null);
        }

        mAgentWeb.getWebCreator().getWebView().setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mWebView != null && mWebView.canGoBack()) {
//                        WebBackForwardList history = mWebView.copyBackForwardList();
//                        if (history.getCurrentItem().getUrl().contains(Constants.getBaseUrl(Constants.SERVER_TYPE) + "index.html")) {
//                            return false;
//                        }
                        mWebView.goBack();
                        return true;
                    }
                }
                return false;
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

    }


    @Override
    public int getStatusBarColor() {
        return 0;
    }

    @Override
    public int getDrawableStatusBar() {
        return 0;
    }


    /**
     * @return IAgentWebSettings
     */
    public IAgentWebSettings getSettings() {
        return new AbsAgentWebSettings() {
            private AgentWeb mAgentWeb;

            @Override
            protected void bindAgentWebSupport(AgentWeb agentWeb) {
                this.mAgentWeb = agentWeb;
            }

            /**
             * AgentWeb 4.0.0 内部删除了 DownloadListener 监听 ，以及相关API ，将 Download 部分完全抽离出来独立一个库，
             * 如果你需要使用 AgentWeb Download 部分 ， 请依赖上 compile 'com.just.agentweb:download:4.0.0 ，
             * 如果你需要监听下载结果，请自定义 AgentWebSetting ， New 出 DefaultDownloadImpl，传入DownloadListenerAdapter
             * 实现进度或者结果监听，例如下面这个例子，如果你不需要监听进度，或者下载结果，下面 setDownloader 的例子可以忽略。
             * @param webView
             * @param downloadListener
             * @return WebListenerManager
             */
            @Override
            public WebListenerManager setDownloader(WebView webView, android.webkit.DownloadListener downloadListener) {
                return super.setDownloader(webView,
                        DefaultDownloadImpl
                                .create((Activity) webView.getContext(),
                                        webView,
                                        mDownloadListenerAdapter,
                                        mDownloadListenerAdapter,
                                        this.mAgentWeb.getPermissionInterceptor()));
            }
        };
    }

    protected DownloadListenerAdapter mDownloadListenerAdapter = new DownloadListenerAdapter() {


        @Override
        public boolean onStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength, AgentWebDownloader.Extra extra) {
            extra.setOpenBreakPointDownload(true)
                    .setIcon(R.drawable.ic_file_download_black_24dp)
                    .setConnectTimeOut(6000)
                    .setBlockMaxTime(2000)
                    .setDownloadTimeOut(60L * 5L * 1000L)
                    .setAutoOpen(true)
                    .setForceDownload(false);
            return false;
        }


        @Override
        public void onBindService(String url, DownloadingService downloadingService) {
            super.onBindService(url, downloadingService);
            mDownloadingService = downloadingService;
            LogUtils.i("TAG", "onBindService:" + url + "  DownloadingService:" + downloadingService);
        }


        @Override
        public void onUnbindService(String url, DownloadingService downloadingService) {
            super.onUnbindService(url, downloadingService);
            mDownloadingService = null;
            LogUtils.i("TAG", "onUnbindService:" + url);
        }


        @Override
        public void onProgress(String url, long loaded, long length, long usedTime) {
            int mProgress = (int) ((loaded) / Float.valueOf(length) * 100);
            LogUtils.i("TAG", "onProgress:" + mProgress);
            super.onProgress(url, loaded, length, usedTime);
        }


        @Override
        public boolean onResult(String path, String url, Throwable throwable) {
            if (null == throwable) {
                //do you work
            } else {

            }
            return false;
        }
    };
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            LogUtil.e("加载地址--》" + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            super.onPageFinished(view, url);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }

//        /**
//         * api>=21调用
//         * @param view
//         * @param request
//         * @return
//         */
//        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
//            if (request != null && request.getUrl() != null && request.getMethod().equalsIgnoreCase("get")) {
////                LogUtil.e("shouldInterceptRequest url-->" + request.getUrl());
//                String scheme = request.getUrl().getScheme().trim();
//                if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) {
//                    if (request.getUrl().toString().contains(".html")) {
//                        try {
//                            URL url = new URL(InjectParamsUtil.verrificationToken(request.getUrl().toString()));
//                            LogUtil.e("url-->" + url);
//                            URLConnection connection = url.openConnection();
//                            if (connection.getInputStream().toString().length() < 120) {
//                                String value = IOUtils.toString(connection.getInputStream(), "UTF-8");
//                                if (value.startsWith("{")) {
//                                    HttpResult httpResult = JSONObject.parseObject(value, HttpResult.class);
//                                    if (httpResult != null) {
//                                        LogUtil.e(httpResult.toString());
//                                        if (Constants.LOGIN_OUT_CODE.equals(httpResult.getCode())) {
//                                            LogUtil.e("token过期");
//                                            HttpResult refreshHttpResult = RefreshTokenSynchronizationRequest.synchronizationRefreshToken();
//                                            LogUtil.e("refreshHttpResult-->" + refreshHttpResult);
//                                            if (refreshHttpResult != null && Constants.SUCCESS_CODE.equals(refreshHttpResult.getCode())) {
//                                                mActivity.runOnUiThread(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        String newUrl = InjectParamsUtil.injectIsParams(request.getUrl().toString());
//                                                        LogUtil.e("newUrl-->" + newUrl);
//                                                        //刷新
//                                                        isRefresh = true;
//                                                        mWebView.loadUrl(newUrl);
//                                                    }
//                                                });
//                                            } else {
//                                                LoginActivity.startAction(MainNewActivity.this);
//                                                SPUtils.removeLoginEntity(MainNewActivity.this, null);
//                                                mActivity.finish();
//                                            }
////                                            LoginActivity.startAction(MainNewActivity.this);
////                                            SPUtils.removeLoginEntity(MainNewActivity.this, null);
////                                            mActivity.finish();
//                                        }
//                                    }
//                                }
//                            } else {
//                                connection.getInputStream().close();
//                            }
//                            return null;
//                        } catch (MalformedURLException e) {
//                            e.printStackTrace();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//            return null;
//        }

//        /**
//         * api<21调用
//         * @param view
//         * @param url
//         * @return
//         */
//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
////            LogUtil.e("shouldInterceptRequest url-->" + url);
//            if (url.contains(".html")) {
//                try {
//                    URL url1 = new URL(InjectParamsUtil.verrificationToken(url));
//                    URLConnection connection = url1.openConnection();
//                    if (connection.getInputStream().toString().length() < 120) {
//                        String value = IOUtils.toString(connection.getInputStream(), "UTF-8");
//                        if (value.startsWith("{")) {
//                            mHttpResult = JSONObject.parseObject(value, HttpResult.class);
//                            if (mHttpResult != null) {
//                                if (Constants.LOGIN_OUT_CODE.equals(mHttpResult.getCode())) {
//                                    HttpResult refreshHttpResult = RefreshTokenSynchronizationRequest.synchronizationRefreshToken();
//                                    if (refreshHttpResult != null && Constants.SUCCESS_CODE.equals(refreshHttpResult.getCode())) {
//                                        mActivity.runOnUiThread(new Runnable() {
//                                            @Override
//                                            public void run() {
//                                                String newUrl = InjectParamsUtil.injectIsParams(url);
//                                                LogUtil.e("newUrl-->" + newUrl);
//                                                //刷新
//                                                isRefresh = true;
//                                                mWebView.loadUrl(newUrl);
//                                            }
//                                        });
//                                    } else {
//                                        LoginActivity.startAction(MainNewActivity.this);
//                                        SPUtils.removeLoginEntity(MainNewActivity.this, null);
//                                        mActivity.finish();
//                                    }
////                                    LoginActivity.startAction(MainNewActivity.this);
////                                    SPUtils.removeLoginEntity(MainNewActivity.this, null);
////                                    mActivity.finish();
//                                }
//                            }
//                        }
//                    } else {
//                        connection.getInputStream().close();
//                    }
//
//                    return null;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            return null;
//        }

    };


    /**
     * 隐藏底部栏方法
     */
    private void hideBottom() {
        try {
            //定义javaScript方法
            String javascript = "javascript:function hideBottom() { "
                    + "document.getElementsByClassName('tabbar')[0].style.display='none'"
                    + "}";

            //加载方法
            mWebView.loadUrl(javascript);
            //执行方法
            mWebView.loadUrl("javascript:hideBottom();");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        AgentWebConfig.clearDiskCache(MainNewActivity.this);
        mWebView.clearCache(true);
        mAgentWeb.getWebLifeCycle().onDestroy();
        WebStorage.getInstance().deleteAllData();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("结果码-->" + resultCode + "\n请求码--》" + requestCode);
        if (resultCode == 0) {
            if (mUploadCallbackAboveFive != null) {
                mUploadCallbackAboveFive.onReceiveValue(null);
                mUploadCallbackAboveFive = null;
            }
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            return;
        }
        if (resultCode == SCAN_RESULT_CODE) {
            String scanResult = null;
            if (data != null) {
                scanResult = data.getStringExtra("scanResult");
            }
            mWebView.loadUrl("javascript:getScanCode(\"" + scanResult + "\");");
            return;
        }

        switch (requestCode) {
            //拍照
            case GET_PICTURE_TAKE_PHOTO:
                userImgFile = cutPicture(userImgFile);
                break;
            //选择照片
            case GET_PICTURE_SELECT_PHOTO:
                userImgFile = ImageSelector.getPhotoFromIntent(data, MainNewActivity.this);
                userImgFile = cutPicture(userImgFile);
                break;
            //裁剪照片
            case CUT_PHOTO:
                if (resultCode == Activity.RESULT_OK) {
                    compressImage(userImgFile);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 压缩图片
     *
     * @param file
     */
    public void compressImage(File file) {
        List<File> list = new ArrayList<>();
        list.add(file);
        BitmapUtil.compressFiles(list, new ICompressImageResponse() {
            @Override
            public void onSuccess(List<File> images) {
                File imgFile = images.get(0);
                Uri result = ImageSelector.toURI(MainNewActivity.this, imgFile);
                if (null != mUploadMessage && null == mUploadCallbackAboveFive) {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }

                if (null == mUploadMessage && null != mUploadCallbackAboveFive) {
                    mUploadCallbackAboveFive.onReceiveValue(new Uri[]{result});
                    mUploadCallbackAboveFive = null;
                }
            }

            @Override
            public void onMarch() {

            }

            @Override
            public void onFail() {

            }

            @Override
            public void onFinish() {

            }
        });
    }

    /**
     * 显示图片选择器
     *
     * @param context
     * @param view
     */
    public void showSelector(final Context context, View view) {
        PopupGetPictureView popupGetPictureView = new PopupGetPictureView(context, new
                PopupGetPictureView.GetPicture() {
                    @Override
                    public void takePhoto(View v) {
                        if (PermissionUtils.checkTakePhotoPermission(context)) {
                            userImgFile = takePicture(GET_PICTURE_TAKE_PHOTO);
                        }
                    }

                    @Override
                    public void selectPhoto(View v) {
                        if (PermissionUtils.checkAlbumStroagePermission(context)) {
                            photoPick(GET_PICTURE_SELECT_PHOTO);
                        }
                    }

                    @Override
                    public void cancel(PopupWindow popupWindow) {
                        if (popupWindow.isShowing()) {
                            if (mUploadCallbackAboveFive != null) {
                                mUploadCallbackAboveFive.onReceiveValue(null);
                                mUploadCallbackAboveFive = null;
                            }

                            if (mUploadMessage != null) {
                                mUploadMessage.onReceiveValue(null);
                                mUploadMessage = null;
                            }
                            popupWindow.dismiss();
                        }
                    }
                });
        popupGetPictureView.showPop(view);
    }

    class LocationWebChromeClient extends WebChromeClient {


        private LocationWebChromeClientListener mLocationWebChromeClientListener;

        private GeolocationPermissions.Callback mGeolocationPermissionsCallback;
        private String mOrigin;

        private boolean mShowRequestPermissionRationale = false;

        public LocationWebChromeClient() {
            mLocationWebChromeClientListener = new LocationWebChromeClientListener() {
                @Override
                public boolean onReturnFromLocationSetting(int requestCode) {
                    if (requestCode == REQUEST_CODE_ENABLE_LOCATION) {
                        if (mGeolocationPermissionsCallback != null) {
                            if (isEnabledLocationFunction()) {
                                mGeolocationPermissionsCallback.invoke(mOrigin, true, true);
                            } else {
                                //显然，从设置界面回来还没有开启定位服务，肯定是要拒绝定位了
                                Toast.makeText(MainNewActivity.this, "您拒绝了定位请求", Toast.LENGTH_SHORT).show();
                                mGeolocationPermissionsCallback.invoke(mOrigin, false, false);
                            }
                        }
                        return true;
                    }
                    return false;
                }

                @Override
                public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
                    boolean pass = true;
                    for (Integer result : grantResults) {
                        if (result == PackageManager.PERMISSION_DENIED) {
                            pass = false;
                            break;
                        }
                    }
                    if (pass) {
                        onAccessLocationPermissionGranted();
                    } else {
                        onAccessLocationPermissionRejected();
                    }
                }

                public void onAccessLocationPermissionGranted() {
                    doJudgeLocationServiceEnabled();
                }

                public void onAccessLocationPermissionRejected() {
                    if (mShowRequestPermissionRationale) {
                        ToastUtil.shortShow("您拒绝了定位请求");
                        mGeolocationPermissionsCallback.invoke(mOrigin, false, false);
                    } else {
                        doRequestAppSetting();
                    }
                }
            };
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
//            hideBottom();
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
            this.openFileChooser(uploadMsg);
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
            this.openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            showSelector(MainNewActivity.this, mWebView);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadCallbackAboveFive = filePathCallback;
            showSelector(MainNewActivity.this, mWebView);
            return true;
        }

        private void doRequestAppSetting() {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainNewActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("您禁止了应用获取当前位置的权限，是否前往开启？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent mIntent = new Intent();
                    mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT >= 9) {
                        mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        mIntent.setData(Uri.fromParts("package", MainNewActivity.this.getPackageName(), null));
                    } else if (Build.VERSION.SDK_INT <= 8) {
                        mIntent.setAction(Intent.ACTION_VIEW);
                        mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                        mIntent.putExtra("com.android.settings.ApplicationPkgName", MainNewActivity.this.getPackageName());
                    }
                    startActivity(mIntent);
                }
            });
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    mGeolocationPermissionsCallback.invoke(mOrigin, false, false);
                }
            });
            builder.create().show();
        }

        public LocationWebChromeClientListener getLocationWebChromeClientListener() {
            return mLocationWebChromeClientListener;
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }


        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback geolocationPermissionsCallback) {
            this.mOrigin = origin;
            this.mGeolocationPermissionsCallback = geolocationPermissionsCallback;
            //是否拥有定位权限
            if (hasAccessLocationPermission()) {
                doJudgeLocationServiceEnabled();
            } else {
                //请求定位
                requestAccessLocationPermission();
            }
        }

        private void doJudgeLocationServiceEnabled() {
            //是否开启定位
            if (isEnabledLocationFunction()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainNewActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("正在请求使用您当前的位置，是否许可？");
                builder.setPositiveButton("许可", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mGeolocationPermissionsCallback.invoke(mOrigin, true, true);
                    }
                });
                builder.setNegativeButton("不许可", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mGeolocationPermissionsCallback.invoke(mOrigin, false, false);
                    }
                });
                builder.create().show();
            } else {
                //请求开启定位功能
                requestEnableLocationFunction(mOrigin, mGeolocationPermissionsCallback);
            }
        }

        /**
         * 请求开启定位服务
         */
        private void requestEnableLocationFunction(final String origin, final GeolocationPermissions.Callback geolocationPermissionsCallback) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainNewActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("正在请求使用您当前的位置，是否前往开启定位服务？");
            builder.setPositiveButton("前往开启", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, REQUEST_CODE_ENABLE_LOCATION);
                }
            });
            builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    geolocationPermissionsCallback.invoke(origin, false, false);
                }
            });
            builder.create().show();
        }

        private boolean isEnabledLocationFunction() {
            int locationMode = 0;
            String locationProviders;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    locationMode = Settings.Secure.getInt(MainNewActivity.this.getContentResolver(), Settings.Secure.LOCATION_MODE);
                } catch (Settings.SettingNotFoundException e) {
                    e.printStackTrace();
                    return false;
                }
                return locationMode != Settings.Secure.LOCATION_MODE_OFF;
            } else {
                locationProviders = Settings.Secure.getString(MainNewActivity.this.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                return !TextUtils.isEmpty(locationProviders);
            }
        }

        private boolean hasAccessLocationPermission() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return MainNewActivity.this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED;
            } else {
                return ContextCompat.checkSelfPermission(MainNewActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED;
            }
        }

        private void requestAccessLocationPermission() {
            // 是否要显示问什么要获取权限的解释界面
            /**
             * 什么情况下 shouldShowRequestPermissionRationale会返回true？
             * - 首次请求权限，但是用户禁止了，但是没有勾选“禁止后不再询问”，这样，之后的请求都会返回true
             * 什么情况下，shouldShowRequestPermissionRationale会返回false？
             * - 首次请求权限或者请求权限时，用户勾选了“禁止后不再询问”，之后的请求都会返回false
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    //请求过定位权限，但是被用户拒绝了（但是没有勾选“禁止后不再询问”）
                    // 显示解释权限用途的界面，然后再继续请求权限
                    mShowRequestPermissionRationale = true;
                } else {
                    mShowRequestPermissionRationale = false;
                }
            } else {
                mShowRequestPermissionRationale = false;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(MainNewActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("正在请求使用您当前的位置，是否许可应用获取当前位置权限？");
            builder.setPositiveButton(" 是 ", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                                REQUEST_CODE_ACCESS_LOCATION_PERMISSION);
                    } else {
                        //额，版本低，正常情况下，安装默认许可，然鹅，国产ROM各种魔改，有阔轮提前实现了单独授权
                        doRequestAppSetting();
                    }
                }
            });
            builder.setNegativeButton(" 否 ", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    mGeolocationPermissionsCallback.invoke(mOrigin, false, false);
                }
            });
            builder.create().show();
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mWebChromeClient != null && mWebChromeClient.getLocationWebChromeClientListener() != null) {
            mWebChromeClient.getLocationWebChromeClientListener().onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    interface LocationWebChromeClientListener {

        /**
         * 用户从开启定位页面回来了
         */
        boolean onReturnFromLocationSetting(int requestCode);

        /**
         * 请求权限结果
         */
        void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults);
    }

    private final class JavaScriptInterface {
        public Activity activity;


        public JavaScriptInterface(Activity activity) {
            this.activity = activity;
        }

        @JavascriptInterface
        public void scanCode() {
//            startActivityForResult(new Intent(activity, ScanActivity.class), SCAN_REQUEST_CODE);
        }

        @JavascriptInterface
        public void callPhone(String phone) {
//            try {
//                Intent intent = new Intent();
//                intent.setAction(Intent.ACTION_CALL);
//                intent.setData(Uri.parse("tel:" + phone));
//                //开启系统拨号器
//                activity.startActivity(intent);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

        }

        @JavascriptInterface
        public void shareQRCode(String base64) {
//            FileOutputStream outputStream = null;
//            try {
//                Bitmap bitmap = ShareUtils.stringToBitmap(base64);
//                File fileDir = activity.getExternalFilesDir(null);
//                assert fileDir != null;
//                fileDir.mkdirs();
//                File file = new File(fileDir, "share.png");
//                outputStream = new FileOutputStream(file);
//                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
//                outputStream.close();
//                ShareEntity shareEntity = new ShareEntity();
//                shareEntity.setImageData(bitmap);
//                shareEntity.setImagePath(file.getAbsolutePath());
//                JShareUtil.getInstance().showBroadView(activity, Platform.SHARE_IMAGE, shareEntity);
////                ShareUtils.share(activity, file);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }

        @JavascriptInterface
        public void downBase64(String... urlList) {
//            LogUtil.e("开始下载");
//            LogUtil.d(urlList);
//            for (String url : urlList) {
//                if (TextUtils.isEmpty(url)) {
//                    ToastUtil.shortShow("资源文件找不到，无法保存");
//                    return;
//                }
//                try {
//                    LoadingViewDialog.getInstance().show(activity);
//                    SaveImageUtils.getInstance().saveImage(activity, url);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    ToastUtil.shortShow("下载地址异常，无法下载图片");
//                }
//            }
        }

        @JavascriptInterface
        public void androidGoBack() {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    }
                }
            });

        }

        @JavascriptInterface
        public void authentica() {
//            RealNameAuthenticationActivity.startAction(activity);
        }

        /**
         * 登录成功
         *
         * @param token
         * @param userId
         */
        @JavascriptInterface
        public void loginSuccess(String token, String userId) {
            LogUtil.e("js接口调用 " + "token " + token + "  userId " + userId);
            if (!TextUtils.isEmpty((String) SPUtils.get(App.getInstance().getApplicationContext(), Constants.USER_CODE, ""))) {
                if (!TextUtils.equals(userId, (String) SPUtils.get(App.getInstance().getApplicationContext(), Constants.USER_CODE, ""))) {
                    SPUtils.put(App.getInstance().getApplicationContext(), Constants.ACCESS_TOKEN, token);
                    if (!TextUtils.isEmpty(userId)) {
                        LogUtil.e("userId-->" + userId);
                        SPUtils.put(App.getInstance().getApplicationContext(), Constants.USER_CODE, userId);
//                        TagAliasSetting.addTagAlias(App.getInstance().getApplicationContext(), userId);
                    }
                }
            } else {
                SPUtils.put(App.getInstance().getApplicationContext(), Constants.ACCESS_TOKEN, token);
                if (!TextUtils.isEmpty(userId)) {
                    LogUtil.e("userId-->" + userId);
                    SPUtils.put(App.getInstance().getApplicationContext(), Constants.USER_CODE, userId);
//                    TagAliasSetting.addTagAlias(App.getInstance().getApplicationContext(), userId);
                }
            }

        }

        /**
         * 退出登录
         */
        @JavascriptInterface
        public void doLoginOut() {
            LogUtil.e("js接口调用 退出登录");
            String userCode = (String) SPUtils.get(activity, Constants.USER_CODE, "");
            if (!TextUtils.isEmpty(userCode)) {
                LogUtil.e("userCode-->" + userCode);
//                TagAliasSetting.removeTagAlias(activity, userCode);
            }

            SPUtils.put(App.getInstance().getApplicationContext(), Constants.USER_CODE, "");
            stopVoiceService();
            ToastUtil.shortShow("退出登录");
        }

        /**
         * 省电白名单设置
         */
        @JavascriptInterface
        public void powerSaving() {
            try {
                BatteryWhiteList.showBatteryOptimization(activity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 后台运行设置
         */
        @JavascriptInterface
        public void setBackgrounder() {
            SystemSetting.onViewClicked(SystemSetting.getDeviceType(), activity);
        }

        /**
         * 打开或或关闭语音播报
         *
         * @param isOpen
         */
        @JavascriptInterface
        public void openOrCloseVoice(boolean isOpen) {
            LogUtil.e("isOpen " + isOpen);
            SPUtils.put(App.getInstance().getApplicationContext(), (String) SPUtils.get(App.getInstance().getApplicationContext(), Constants.USER_CODE, "") + Constants.VOICE_OPEN_STATUS, isOpen);

            if (isOpen) {
                if (!isStartService()) {
                                    startService(new Intent(activity, KeepLiveVoiceService.class));
                    //         Android 8.0使用startForegroundService在前台启动新服务
//                    Intent voiceService = new Intent(activity, VoiceService.class);
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                        startForegroundService(voiceService);
//                    } else {
//                        startService(voiceService);
//                    }
                }


            } else {
                if (isStartService()) {
                    stopVoiceService();
                }
                VoiceSpeaker.getInstance().closeLoudnessEnhancer();
            }
        }
    }

    private void stopVoiceService() {
        stopService(new Intent(this, KeepLiveVoiceService.class));

        if (ServiceUtils.isServiceRunning(this, "com.fengniaoxls.fengniaonewretail.jpush.voice.service.KeepLiveVoiceService")) {
            com.freak.httphelper.log.LogUtil.e("锁屏   正在运行");
        } else {
            com.freak.httphelper.log.LogUtil.e("锁屏   停止运行");
        }
    }

    public boolean isStartService() {
        if (ServiceUtils.isServiceRunning(this, "com.fengniaoxls.fengniaonewretail.jpush.voice.service.KeepLiveVoiceService")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 相册选择图片
     *
     * @return
     */
    public void photoPick(int requestCode) {
        try {
            Intent getAlbum = new Intent(Intent.ACTION_PICK);
            getAlbum.setType("image/*");
            startActivityForResult(getAlbum, requestCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发起裁剪
     */
    public File cutPicture(File selectPhoto) {
        try {
            if (selectPhoto == null) {
                return null;
            }

            File dir = ImageSelector.getInstance().getTakePhotoCacheDir();
            String key = String.valueOf(System.currentTimeMillis());
            if (!dir.exists()) {
                dir.mkdir();
            }
            File outfile = new File(dir, key + ".jpg");
            Uri uri = toURI(selectPhoto);
            Uri outUri = Uri.fromFile(outfile);
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // 图片来源
            cropIntent.setDataAndType(uri, "image/*");
            // 设置剪裁剪属性
            cropIntent.putExtra("crop", "true");
            //    cropIntent.putExtra("aspectX", 1);
            //   cropIntent.putExtra("aspectY", 3);
            // 输出的坐标
            cropIntent.putExtra("outputX", 500);
            cropIntent.putExtra("outputY", 500);
            // 返回剪裁的图片数据
            cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
            cropIntent.putExtra("return-data", false);
            startActivityForResult(cropIntent,
                    CUT_PHOTO);
            return outfile;
        } catch (Exception e) {
            return selectPhoto;
        }
    }

    public Uri toURI(File file) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            return Uri.fromFile(file);
        } else {
            return FileProvider.getUriForFile(
                    App.getInstance().getApplicationContext(),
                    BuildConfig.APPLICATION_ID + ".fileProvider",
                    file);
        }
    }

    /**
     * 发起拍照
     */
    public File takePicture(int requestCode) {
        String imgUrl = "";
        File f = null;
        try {
            File dir = ImageSelector.getInstance().getTakePhotoCacheDir();
            String key = String.valueOf(System.currentTimeMillis());
            if (!dir.exists()) {
                dir.mkdir();
            }
            f = new File(dir, key + ".jpg");
            imgUrl = f.getAbsolutePath();
            Uri u = toURI(f);
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            intent.putExtra("imgurl", imgUrl);
            startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - mTime > 1500) {
            ToastUtil.shortShow("再按一次退出程序");
            mTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }
}
